import { loginAPI } from '@/api/user'
import router from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  saveToken(state, token) {
    state.token = token
  },
  saveInfo(state, data) {
    state.userInfo = data
  }
}

const actions = {
  // 登录功能
  async loginActions(context, data) {
    const res = await loginAPI(data)
    // 实现 vuex 持久化存储
    context.commit('saveToken', res.data.data.token.token)
    context.commit('saveInfo', res.data.data.user)
    setToken(res.data.data.token.token)
    // 判断是否登录成功 给出相应提示
    if (res.data.msg === 'ok') {
      Message.success('登录成功')
      router.push('/')
    } else {
      Message.error(res.data.msg)
    }
  }
  // 获取用户信息
  // async userActions(context, data){
  //   const res = await
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

